using UnityEngine;
using System.Collections;

public class  UserController : MonoBehaviour {
	public float maxSpeed=5;
	public bool isPlayerOne=true;
	private string horizontalMove, jump, grab;
	public float jumpSpeed=1;
	public float speed=1;
	public bool grounded=false;
	public float gravity=2;
	private Vector3 moveDirection=new Vector3(0,0,0);
	// Use this for initialization
	public void Start () 
	{
		if(isPlayerOne)
		{
			horizontalMove="P1 Horizontal";
			jump="P1 Jump";
		}
	
	}
	
	public void Update()
	{
		transform.position=new Vector3(transform.position.x,transform.position.y,0.0f);
	}
	
	// Update is called once per frame
	public void FixedUpdate () 
	{
		
		if (grounded) 
		{
			// We are grounded, so recalculate movedirection directly from axes
			moveDirection = new Vector3(Input.GetAxis(horizontalMove)*speed, 0, 0);
			
			if(Input.GetAxis(horizontalMove)!=0)
			{
				Debug.Log(Input.GetAxis(horizontalMove));
			}
			
			
			if (Input.GetButton (jump)) 
			{
				moveDirection.y = jumpSpeed;
			}
		}

		// Apply gravity
		moveDirection.y -= gravity * Time.deltaTime;
		
		// Move the controller
		//CharacterController controller = GetComponent<CharacterController>();
		//CollisionFlags flags = controller.Move(moveDirection * Time.deltaTime);
		//grounded = (flags & CollisionFlags.CollidedBelow) != 0;
		Rigidbody body = GetComponent<Rigidbody>();
		//body.AddForce(moveDirection * Time.deltaTime);
		body.velocity = moveDirection;
		
	}
	
	public void OnCollisionStay(Collision collision)
	{
		
		
		/*foreach(ContactPoint contact  in collision.contacts) 
		{
			Debug.DrawRay(contact.point,new Vector3(0,10,0));
            if (contact.point.y < transform.position.y && !(contact.point.x<collider.bounds.min.x||contact.point.x>collider.bounds.max.x))
			{
				
				grounded=true;
				break; 
			}
		}*/
		contactBeneath(collision);
	}
	public void OnCollisionExit(Collision collisionInfo)
	{
		if(collisionInfo.transform.position.y<transform.position.y)
		{
			grounded=false;
		}
	}
	
	private void contactBeneath(Collision collision)
	{
		bool inFront=false, behind=false;
		foreach(ContactPoint contact  in collision.contacts) 
		{
            if (contact.point.y < transform.position.y)
			{
				if(contact.point.x>collider.bounds.min.x+.1&&contact.point.x<collider.bounds.max.x-.1)
				{
					grounded=true;
					break;
				}
				else if(contact.point.x<=collider.bounds.min.x+.1)
				{
					
					behind=true;
				}
				else if(contact.point.x>=collider.bounds.max.x-.1)
				{
					inFront=true;
				}
				if(behind&&inFront)
				{
					grounded=true;
					break;
				}
			}
		}
	}
	
		
}
